package repository

import (
	"strconv"
	"yak.admin/src/entity"
	"yak.admin/src/service"
)

type ReportRepository struct {
	UserId   uint
	Page     int `form:"page"`
	Pagesize int `form:"per-page"`
}

func (repository *ReportRepository) FindAll() []map[string]interface{} {
	table := "report_log_" + strconv.Itoa(int(repository.UserId%10))
	reader := new(service.ReaderQuery).CreateQuery(table).
		WithEQ("user_id", repository.UserId).
		WithPreloads([]string{"DrugReport", "DeviceReport"}).
		WithPage(repository.Page).WithPageSize(repository.Pagesize).
		WithOrder("created_at", "desc")

	var reports []*entity.ReportLog
	reader.Reader(&reports)
	drug := DrugReportRepository{}
	riskLabels := drug.DrugRiskLabels()
	categoryLabels := drug.DrugCategoryLabels()
	statusLabels := drug.StatusLabels()

	return reader.Datalist(reports, len(reports), func(index int, item interface{}) map[string]interface{} {
		m := item.(*entity.ReportLog)
		if m.Type == 2 {
			return map[string]interface{}{
				"_serial":        reader.AsSerial(index),
				"id":             m.Pid,
				"number":         m.DeviceReport.Number,
				"report_at":      reader.AsDatetime(m.DeviceReport.ReportedAt),
				"produce_name":   m.DeviceReport.ProduceName,
				"produce_number": m.DeviceReport.ProduceNumber,
				"produce_id":     m.DeviceReport.ProduceId,
				"status":         m.DeviceReport.Status,
				"status_label":   statusLabels[m.DeviceReport.Status],
				"type":           m.Type,
			}
		}
		return map[string]interface{}{
			"_serial":      reader.AsSerial(index),
			"id":           m.Pid,
			"number":       m.DrugReport.Number,
			"report_at":    reader.AsDatetime(m.DrugReport.ReportedAt),
			"title":        m.DrugReport.Title,
			"category":     categoryLabels[m.DrugReport.CategoryRefer],
			"risk":         reader.AsCheckListString(m.DrugReport.RiskRefer, riskLabels),
			"status":       m.DrugReport.Status,
			"status_label": statusLabels[m.DrugReport.Status],
			"type":         m.Type,
		}
	})
}
